package com.ys.service.finance.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.dto.AddDto;
import com.ys.entity.finance.TcwWanliSupplementary;
import com.ys.entity.finance.TcwWanliSupplementaryItem;
import com.ys.entity.flow.YspModel;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsCol;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.mapper.finance.FinanceMapper;
import com.ys.mapper.finance.TcwWanliSupplementaryItemMapper;
import com.ys.mapper.finance.TcwWanliSupplementaryMapper;
import com.ys.service.finance.TcwWanliSupplementaryService;
import com.ys.service.flow.YspTaskService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;

/**
 * 万里汇补账
 */
@Service("tcwWanliSupplementaryService")
public class TcwWanliSupplementaryServiceImpl implements TcwWanliSupplementaryService {

	@Autowired
	private TcwWanliSupplementaryMapper tcwWanliSupplementaryMapper;

	@Autowired
	private TcwWanliSupplementaryItemMapper tcwWanliSupplementaryItemMapper;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private FinanceMapper financeMapper;

	@Autowired
	private YspTaskService yspTaskService;
	
	private String yzMsg(Map<String, Object> infoMap){
		//验证导入字段
		String backMsg = "";
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+ MenuId.TCW_WanliSupplementary)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		try {
			backMsg = checkUtil.checkTableColLengthAndDataType(
					"TCW_WanliSupplementary",
					listField,
					infoMap,
					ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1
			);
			if(backMsg!=null && !"".equals(backMsg)){//若有误，则跳过这条信息
				return backMsg;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/*
	 * 新增
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R add(Map<String, Object> params, String subData) throws Exception {
		//验证
		String msg = yzMsg(params);
		if (msg != null){
			return R.error(msg);
		}
		TcwWanliSupplementary tcwWanliSupplementary = JSON.parseObject(JSON.toJSONString(params), TcwWanliSupplementary.class);
		if (new TcwWanliSupplementary().setBid(tcwWanliSupplementary.getBid()).count() != 0){
			return R.error("该单号已存在，核实后再操作!");
		}
		// 验证是否有详情数据
		JSONArray detailJA = JSON.parseArray(subData);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		}

		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();

		tcwWanliSupplementary.setStatus(0);
		tcwWanliSupplementary.setOperatorChangeId(String.valueOf(tsUserChange.getId()));
		tcwWanliSupplementary.setEffectStock(FlowEnum.EffectStock.NOT_EFFECT.value);
		tcwWanliSupplementaryMapper.insert(tcwWanliSupplementary);
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			TcwWanliSupplementaryItem tcwWanliSupplementaryItem = JSON.parseObject(JSON.toJSONString(detailJO), TcwWanliSupplementaryItem.class);
			tcwWanliSupplementaryItem.setPbid(tcwWanliSupplementary.getBid());
			tcwWanliSupplementaryItemMapper.insert(tcwWanliSupplementaryItem);
		}


		YsMenu ysMenu = new YsMenu().setId(MenuId.TCW_WanliSupplementary).queryFirst();
		if (ysMenu.getFlowModelId().longValue() != 0L) {
			YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
			String codeModel = yspModel.getCode();
			String createUserId = ShiroUtils.getUserId();
			yspTaskService.init(codeModel, tcwWanliSupplementary.getBid(), createUserId);
		}

		return R.ok(AddDto.gotoEdit("/web/finance/tcwWanliSupplementary/toEdit?bid=" + tcwWanliSupplementary.getBid()));
	}



	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R edit(Map<String, Object> params,String subData) throws Exception {
//验证
		String msg = yzMsg(params);
		if (msg != null){
			return R.error(msg);
		}
		TcwWanliSupplementary tcwWanliSupplementary = JSON.parseObject(JSON.toJSONString(params), TcwWanliSupplementary.class);
		if (new TcwWanliSupplementary().setBid(tcwWanliSupplementary.getBid()).where("A.id != " + tcwWanliSupplementary.getId()).count() != 0){
			return R.error("该单号已存在，核实后再操作!");
		}

		// 验证是否有详情数据
		JSONArray detailJA = JSON.parseArray(subData);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		}

		//判断是否实在制单中
		Integer flowState = yspTaskService.flowState(tcwWanliSupplementary.getBid());

		if (flowState != 0){
			return R.error("个税付款单不是制单中,不允许保存!");
		}
		tcwWanliSupplementaryMapper.update(tcwWanliSupplementary);

		//批量删除
		financeMapper.deleteTcwWanliSupplementaryItemBid(tcwWanliSupplementary.getBid());

//		for (int i = 0; i < detailJA.size(); i++) {
//			JSONObject detailJO = detailJA.getJSONObject(i);
//			TcwWanliSupplementaryItem tcwWanliSupplementaryItem = JSON.parseObject(JSON.toJSONString(detailJO), TcwWanliSupplementaryItem.class);
//			tcwWanliSupplementaryItem.setUserPayApplyItemId(Long.valueOf(detailJO.get("userPayApplyItemId").toString()));
//			tcwWanliSupplementaryItem.setIncomePayBid(tcwWanliSupplementary.getBid());
//			if (detailJO.get("vbzXq") != null){
//				tcwWanliSupplementaryItem.setVbz(detailJO.get("vbzXq").toString());
//			}
//			if(detailJO.get("vgsbm") == null){
//				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//				return R.error("运营公司不能为空,不允许保存!");
//			}
//			tcwWanliSupplementaryItemMapper.insert(tcwWanliSupplementaryItem);
//		}

		return R.ok(AddDto.gotoEdit("/web/finance/tcwWanliSupplementary/toEdit?bid=" + tcwWanliSupplementary.getBid()));

	}

	@Override
	@Transactional
	public R deleteTrue(Long id) throws Exception {
		if (id == null) {
			return R.error("ID不能为空");
		}
		TcwWanliSupplementary entity = new TcwWanliSupplementary().setId(id).queryFirst();
		if (entity.getEffectStock() == FlowEnum.EffectStock.EFFECTED.value) {
			return R.error("已生效数据无法删除");
		}

		// 删除主数据
		tcwWanliSupplementaryMapper.deleteTrue(id);
		return R.ok();
	}

	@Override
	@Transactional
	public R flowPass(String bid, String loginUserId) throws Exception {

		try {
			Flow f = yspTaskService.flowPass(bid, loginUserId);
			if (f.getCode() == Flow.Code.FAILED.value) {
				return R.error(f.getMsg());
			} else {

				if (f.getState() == Flow.State.FINISH.value) {
					flowFinish(bid);
				}
				return R.ok();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}

	@Override
	public R flowRefuse(String bid, String reason, String loginUserId) throws Exception {

		R r = yspTaskService.flowRefuse(bid, reason, loginUserId);
		return r;
	}

	@Override
	@Transactional
	public void flowFinish(String bid) throws Exception {

		TcwWanliSupplementary entity = new TcwWanliSupplementary().setBid(bid).queryFirst();

		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
			return;
		}

		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		tcwWanliSupplementaryMapper.update(entity);
	}


	//获取列表数据
	@Override
	@Transactional
	public Map<String,Object> getExtraParam( String bid) throws Exception{
		Map<String, Object> extraParam = new TcwWanliSupplementary().setBid(bid)
				.addLeftJoin("YS_ProcInst Ysp ON Ysp.bid = A.bid")//流程表
				.addField("Ysp.updateTime AS updateTime1")
				.queryFirstMap();
		return extraParam;
	}
	//获取子列表数据
	@Override
	@Transactional
	public List<Map<String, Object>> getItemList( String bid) throws Exception{
		List<Map<String, Object>> itemList = new TcwWanliSupplementaryItem()
				.setPbid(bid)
				.addLeftJoin("TCW_WanliSupplementary B ON B.Bid = A.Pbid")
				.addLeftJoin("TCW_DepositPlatform C ON C.Code = A.DepositPlatformCode ")
				.addLeftJoin("TB_CompanyInfo O ON O.Vid = C.CompanyVid ")
				.addField("C.PlatformName AS platformName")
				.addField("C.Code AS depositPlatformCode")
				.addField("C.Name AS name")
				.addField("C.CompanyVid AS companyVid")
				.addField("C.CompanyVid AS vname")
				.addField("O.Vname AS vname")
				.addField("B.Remark AS remark")
				.queryMap();
		return itemList;
	}
}
